package com.lims.novel;

import com.lims.utils.FileUtil;
import org.junit.platform.commons.util.StringUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @author lmshe
 * @create 2018-08-22 20:41
 * @desc
 */
public class Shuba23 {
    //笔趣阁地址
    public final static String BIQUGE_URL = "https://23shu8.net/txt/";

    /**
     * @author lmshe
     * @create 20:46 2018/8/22
     * @desc 获取小说主要信息
     */
    public static NovelDto getNovelMsg(String serialNum) {
        //获取网页html内容
        String date = getData(BIQUGE_URL + serialNum);
        if (StringUtils.isBlank(date)) {
            System.out.println("获取小说章节信息失败");
            return null;
        }
        System.out.println("小说章节信息：" + date);
        //解析分割小说主体内容
        NovelDto novelDto;
        try {
            String str = date.substring(date.indexOf("id=\"info\""));
            //书名
            String novelName = str.substring(str.indexOf("<h1>") + "<h1>".length(), str.indexOf("</h1>"));
            if (novelName.indexOf("（") > 0) {
                novelName = novelName.substring(0, novelName.indexOf("（"));
            }
            //作者
            String author = str.substring(str.indexOf("者：") + "者：".length(), str.indexOf("</p>"));

            //最后更新
            str = str.substring(str.indexOf("最后更新：") + "最后更新：".length());
            String lastUpdateTime = str.substring(0, str.indexOf("</p>"));

            //简介
            str = str.substring(str.indexOf("id=\"intro\"") + "id=\"intro\"".length());
            String introduction = str.substring(str.indexOf("<p>") + "<p>".length(), str.indexOf("</p>"));

            //小说dto
            novelDto = new NovelDto();
            novelDto.setNovelName(novelName);
            novelDto.setAuthor(author);
            novelDto.setLastUpdateTime(lastUpdateTime);
            novelDto.setIntroduction(introduction);

            //解析分割章节内容
            List<NovelChapterDto> NovelChapterList = new ArrayList<>();
            //切割list
            str = str.substring(str.indexOf("id=\"list\"") + "id=\"list\"".length(), str.indexOf("id=\"footer\""));
            str = str.substring(str.indexOf("<dd>") + "<dd>".length(), str.lastIndexOf("</dd>"));
            String[] chapterArr = str.split("</dd>");
            //遍历
            for (String s : chapterArr) {

                String chapterStr = s;
                //编号
                String chapterSerialNum = chapterStr.substring(chapterStr.indexOf(serialNum + "/") + (serialNum + "/").length(), chapterStr.indexOf(".html"));
                //章节名
                chapterStr = chapterStr.substring(chapterStr.indexOf(".html") + ".html".length());
                String chapterName = chapterStr.substring(chapterStr.indexOf(">") + ">".length(), chapterStr.indexOf("</a>"));
                //加入列表
                NovelChapterDto novelChapterDto = new NovelChapterDto();
                novelChapterDto.setChapterName(chapterName);
                novelChapterDto.setChapterSerialNum(chapterSerialNum);
                NovelChapterList.add(novelChapterDto);
            }
            novelDto.setNovelChapterList(NovelChapterList);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return novelDto;
    }

    /**
     * @author lmshe
     * @create 17:58 2018/8/23
     * @desc 获取章节内容 http://xx/14_14055/9194140.html
     */
    public static String getChapterContent(String serialNum, String chapterSerialNum) {
        String chapterContent = "";
        //获取网页html内容
        String date = getData(BIQUGE_URL + serialNum + "/" + chapterSerialNum + ".html");
        if (StringUtils.isNotBlank(date)) {
            try {
                String str = date.substring(date.indexOf("id=\"content\">") + "id=\"content\">".length());
                chapterContent = str.substring(0, str.indexOf("</div>"));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        chapterContent = chapterContent.replaceAll(" ", "");
        chapterContent = chapterContent.replaceAll("&nbsp;&nbsp;&nbsp;&nbsp;", "#");
        chapterContent = chapterContent.replaceAll("<br/>", "@");
        return chapterContent;
    }

    /**
     * @author lmshe
     * @create 20:38 2018/8/22
     * @desc 模拟浏览器发出请求，并返回网页内容字符串
     */
    public static String getData(String urlStr) {
        StringBuilder result = new StringBuilder();
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setInstanceFollowRedirects(true);
            conn.setRequestProperty("content-type", "text/html");
            conn.connect();
            InputStream is = conn.getInputStream();//拿到输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
            String tempLine;
            while ((tempLine = br.readLine()) != null) {
                result.append(tempLine);
            }
            br.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result.toString();
    }

    public static class NovelChapterDto {
        /**
         * 章节名
         */
        private String chapterName;
        /**
         * 章节编号
         */
        private String chapterSerialNum;

        public String getChapterName() {
            return chapterName;
        }

        public void setChapterName(String chapterName) {
            this.chapterName = chapterName;
        }

        public String getChapterSerialNum() {
            return chapterSerialNum;
        }

        public void setChapterSerialNum(String chapterSerialNum) {
            this.chapterSerialNum = chapterSerialNum;
        }
    }

    public static class NovelDto {
        /**
         * 作者
         */
        private String author;
        /**
         * 小说名称
         */
        private String novelName;
        /**
         * 简介
         */
        private String Introduction;
        /**
         * 最后更新时间
         */
        private String lastUpdateTime;
        /**
         * 章节列表
         */
        private List<NovelChapterDto> NovelChapterList;

        public String getAuthor() {
            return author;
        }

        public void setAuthor(String author) {
            this.author = author;
        }

        public String getNovelName() {
            return novelName;
        }

        public void setNovelName(String novelName) {
            this.novelName = novelName;
        }

        public String getIntroduction() {
            return Introduction;
        }

        public void setIntroduction(String introduction) {
            Introduction = introduction;
        }

        public void setLastUpdateTime(String lastUpdateTime) {
            this.lastUpdateTime = lastUpdateTime;
        }

        public List<NovelChapterDto> getNovelChapterList() {
            return NovelChapterList;
        }

        public void setNovelChapterList(List<NovelChapterDto> novelChapterList) {
            NovelChapterList = novelChapterList;
        }
    }

    public static void main(String[] args) {
        //小说编号
        String serialNum = "209236";
        NovelDto novelDto = getNovelMsg(serialNum);
        //生成小说目录
        String path = System.getProperty("user.dir") + "/log/" + novelDto.getNovelName();
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
        int i = 1;
        StringBuilder sb = new StringBuilder();
        for (NovelChapterDto dto : novelDto.getNovelChapterList()) {
            String chapterContent = getChapterContent(serialNum, dto.getChapterSerialNum());
            sb.append(i);
            i++;
            sb.append(chapterContent);
            sb.append("\n");
            if (i % 5 == 0) {

                sb.append("        //获取网页html内容\n" +
                        "        String date = getData(BIQUGE_URL + serialNum);\n" +
                        "        if (StringUtils.isBlank(date)) {\n" +
                        "            System.out.println(\"获取小说章节信息失败\");\n" +
                        "            return null;\n" +
                        "        }\n" +
                        "        System.out.println(\"小说章节信息：\" + date);\n" +
                        "        //解析分割小说主体内容\n" +
                        "        NovelDto novelDto;\n" +
                        "        try {\n" +
                        "            String str = date.substring(date.indexOf(\"id=\\\"info\\\"\"));\n" +
                        "            //书名\n" +
                        "            String novelName = str.substring(str.indexOf(\"<h1>\") + \"<h1>\".length(), str.indexOf(\"</h1>\"));\n" +
                        "            if (novelName.indexOf(\"（\") > 0) {\n" +
                        "                novelName = novelName.substring(0, novelName.indexOf(\"（\"));\n" +
                        "            }\n" +
                        "            //作者\n" +
                        "            String author = str.substring(str.indexOf(\"者：\") + \"者：\".length(), str.indexOf(\"</p>\"));\n" +
                        "\n" +
                        "            //最后更新\n" +
                        "            str = str.substring(str.indexOf(\"最后更新：\") + \"最后更新：\".length());\n" +
                        "            String lastUpdateTime = str.substring(0, str.indexOf(\"</p>\"));\n" +
                        "\n" +
                        "            //简介\n" +
                        "            str = str.substring(str.indexOf(\"id=\\\"intro\\\"\") + \"id=\\\"intro\\\"\".length());\n" +
                        "            String introduction = str.substring(str.indexOf(\"<p>\") + \"<p>\".length(), str.indexOf(\"</p>\"));\n" +
                        "\n" +
                        "            //小说dto\n" +
                        "            novelDto = new NovelDto();\n" +
                        "            novelDto.setNovelName(novelName);\n" +
                        "            novelDto.setAuthor(author);\n" +
                        "            novelDto.setLastUpdateTime(lastUpdateTime);\n" +
                        "            novelDto.setIntroduction(introduction);\n" +
                        "\n" +
                        "            //解析分割章节内容\n" +
                        "            List<NovelChapterDto> NovelChapterList = new ArrayList<>();\n" +
                        "            //切割list\n" +
                        "            str = str.substring(str.indexOf(\"id=\\\"list\\\"\") + \"id=\\\"list\\\"\".length(), str.indexOf(\"id=\\\"footer\\\"\"));\n" +
                        "            str = str.substring(str.indexOf(\"<dd>\") + \"<dd>\".length(), str.lastIndexOf(\"</dd>\"));\n" +
                        "            String[] chapterArr = str.split(\"</dd>\");\n" +
                        "            //遍历\n" +
                        "            for (String s : chapterArr) {\n" +
                        "\n" +
                        "                String chapterStr = s;\n" +
                        "                //编号\n" +
                        "                String chapterSerialNum = chapterStr.substring(chapterStr.indexOf(serialNum + \"/\") + (serialNum + \"/\").length(), chapterStr.indexOf(\".html\"));\n" +
                        "                //章节名\n" +
                        "                chapterStr = chapterStr.substring(chapterStr.indexOf(\".html\") + \".html\".length());\n" +
                        "                String chapterName = chapterStr.substring(chapterStr.indexOf(\">\") + \">\".length(), chapterStr.indexOf(\"</a>\"));\n" +
                        "                //加入列表\n" +
                        "                NovelChapterDto novelChapterDto = new NovelChapterDto();\n" +
                        "                novelChapterDto.setChapterName(chapterName);\n" +
                        "                novelChapterDto.setChapterSerialNum(chapterSerialNum);\n" +
                        "                NovelChapterList.add(novelChapterDto);\n" +
                        "            }\n" +
                        "            novelDto.setNovelChapterList(NovelChapterList);\n" +
                        "        } catch (Exception e) {\n" +
                        "            e.printStackTrace();\n" +
                        "            return null;\n" +
                        "        }\n" +
                        "        return novelDto;");

                try {
                    String resPath = path + "/" + i + dto.getChapterName() + ".md";
                    FileUtil.write(resPath, sb.toString());
                } catch (Exception e) {
                    System.out.println("生成失败");
                }
                sb = new StringBuilder();
            }
        }

    }
}
